package cn.xo68.ide.plugin.action;

import cn.xo68.core.date.DateTime;
import cn.xo68.ide.plugin.common.component.StarupApplicationComponent;
import cn.xo68.ide.plugin.common.component.ToolSuiteJobManager;
import cn.xo68.ide.plugin.common.git.*;
import cn.xo68.ide.plugin.common.jobs.GitJob;
import cn.xo68.ide.plugin.common.service.Settings;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

public class CommitDataAction extends AnAction {
    private static Logger logger = LoggerFactory.getLogger(CommitDataAction.class);

    @Override
    public void actionPerformed(AnActionEvent e) {
        StarupApplicationComponent starupApplicationComponent =  StarupApplicationComponent.getInstance();
        starupApplicationComponent.setLastOperateProject(e.getProject());
        GitClient gitClient= starupApplicationComponent.getGitClient();

        try {
            gitClient.init();
        } catch (IOException e1) {
            logger.error("git初始化失败...",e);
            return;
        }

        GitElementList waitCommits =gitClient.getWaitCommit();

        if(waitCommits==null || waitCommits.isEmpty()) {
            logger.info("没有需要提交的数据...");
            return;
        }

        List<GitRun> gitRuns=new ArrayList<>();

        if(waitCommits!=null && !waitCommits.isEmpty()) {
            gitRuns.add(new addRun(waitCommits.getPaths()));
        }

        logger.info("提交文件数量： {}",waitCommits.size());
        logger.info("提交文件列表：\n{}",waitCommits.getPrettyString());

        String[] commits=waitCommits.getPaths();
        if(commits!=null && commits.length>0) {
            gitRuns.add(new CommitRun(MessageFormat.format("auto commit By {0}", DateTime.Now().toString()),commits));
        }else {
            gitRuns.add(new CommitRun(MessageFormat.format("auto commit By {0}", DateTime.Now().toString()),null));
        }

        Settings settings=Settings.getInstance();

        gitRuns.add(new PushRun(null,settings.getGitSetting().getUserName(), settings.getGitSetting().getPassword(),false));

        GitJob gitJob=new GitJob("新增、提交、推送文件", gitClient, gitRuns);
        ToolSuiteJobManager toolSuiteJobManager=e.getProject().getComponent(ToolSuiteJobManager.class);
        toolSuiteJobManager.submit(gitJob);
    }
}
